package com.xy.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by XiuYang on 2016/11/18.
 */
@Service
public class FastDFSServiceImpl implements FastDFSService {

    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public String upload(MultipartFile file) throws IOException {
        return upload(file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()));
    }

    @Override
    public String upload(File file) throws IOException {
        return upload(FileUtils.openInputStream(file), file.length(), FilenameUtils.getExtension(file.getAbsolutePath()));
    }

    @Override
    public String upload(InputStream inputStream, long fileSize, String fileExtName) throws IOException {
        StorePath storePath = storageClient.uploadFile(inputStream, fileSize, fileExtName, null);
        inputStream.close();
        return storePath.getFullPath();
    }

    /**
     * 上传从文件
     *
     * @param prefixName
     * @param fileExtName
     * @return
     */
    @Override
    public String uploadSlaveFile(String masterFilePath, File slaveFile, String prefixName, String fileExtName) throws IOException {
        InputStream inputStream = FileUtils.openInputStream(slaveFile);
        StorePath storePath = storageClient.uploadSlaveFile(masterFilePath.substring(0,masterFilePath.indexOf("/"))
            , masterFilePath.substring(masterFilePath.indexOf("/") + 1),inputStream,slaveFile.length(),prefixName,fileExtName);
        inputStream.close();
        return storePath.getFullPath();
    }
}
